package com.tklab.smartcity.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.gson.Gson;
import com.tklab.smartcity.App;
import com.tklab.smartcity.MainActivity;
import com.tklab.smartcity.R;
import com.tklab.smartcity.bean.ResultBean;
import com.tklab.smartcity.util.RetrofitClient;
import com.tklab.smartcity.util.RetrofitUtil;

import java.util.HashMap;
import java.util.Map;

public class loginActivity extends AppCompatActivity {
    private EditText editName;
    private EditText editpwd;
    private Button btnSubmit;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        initView();
    }

    private void initView() {
        editName=findViewById(R.id.editName);
        editpwd=findViewById(R.id.editpassword);
        btnSubmit=findViewById(R.id.btnlogin);

    }

    public void btnSubmit(View view) {
        submit();
    }

    private void submit() {
        String txtuser=editName.getText().toString().trim();
        if(TextUtils.isEmpty(txtuser)){
            Toast.makeText(this,"用户名不能为空",Toast.LENGTH_LONG).show();
            return;
        }
        String txtpwd=editpwd.getText().toString().trim();
        if(TextUtils.isEmpty(txtpwd)){
            Toast.makeText(this,"密码不能为空",Toast.LENGTH_LONG).show();
            return;
        }
        checklogin(txtuser,txtpwd);

    }
    private void checklogin(String username,String txtPwd){
        String url="/prod-api/api/login";
        Map<String ,Object> param=new HashMap<>();
        param.put("username",username);
        param.put("password",txtPwd);
        new RetrofitClient().post(url, param, new RetrofitClient.BackJson() {
            @Override
            public void success(String json) {
                ResultBean resultBean=new Gson().fromJson(json,ResultBean.class);
                if(resultBean.getCode()==200){
                    Intent intent=new Intent(loginActivity.this, MainActivity.class);
                    RetrofitUtil.token=resultBean.getToken();
                    startActivity(intent);
                    finish();
                }else {
                    Toast.makeText(App.context,"登录失败",Toast.LENGTH_LONG).show();
                }
            }
        });
    }
}